package org.biogroovy.util

/**
 * This class contains utility methods for Files.
 */
class FileUtil {
	
	/**
     * This method changes the file extension.
     * @param file  The file to be altered.
     * @param ending The new file extension.
     * @param newParent  The parent directory of the new file.
     */
	static def File changeEnding(File file, String ending, File newParent){
	    int lastPos = file.name.lastIndexOf(".");
	    String rootName = file.name.substring(0, lastPos);
	    File parent = (newParent == null)?file.parent:newParent;
	    return new File (parent, rootName + ending);
	}
	
	/**
	 * This function creates a file name for the HTML.  It replaces all spaces with 
	 * underscores, and appends the .html extension.
	 * @param title  The title of the bookmark.
	 */
	static def String createFileName(String title){
		String newTitle = title.replaceAll(" ", "_");
		newTitle += ".html";
		return newTitle;
	}
	
	/**
	 * This function creates a directory if one does not already exist.
	 * @param tag  The hierarchical tag used to create a subdirectory structure.
	 */
	static def File createDir(String tag){
		File dir = new File(tag);
		if (!dir.exists()){
			dir.mkdirs();
		}
		return dir;
	}


	
	/**
	 * This function downloads the text found at a given URL and writes the contents
	 * out to a file.
	 * @param urlStr  The URL from which to download the file.
	 * @param file    The output file.
	 */
	static def void downloadText(String urlStr, File file){
		URL url = new URL(urlStr);
		
		try {
			def bis = new BufferedInputStream(url.openStream());
			def writer = new FileWriter(file);
			bis.eachLine(){line ->
				writer << "$line \n";
			}
			writer.flush();
			writer.close();
		}catch (IOException ex){
			ex.printStackTrace();
		}
	}


}